#!/usr/bin/python

print "Content-Type: text/html\n"

import os, sys, random
directory = "/usr/share/games/fortunes/"
l = os.listdir(directory)
b = []
for e in l:
    if ".u8" not in e and ".dat" not in e and "de" not in e:
        b.append(e)

s = ""
for e in b:
    f = open(directory+e)
    s+=f.read()
    f.close()
    
bla = s.split("\n%\n")
c = []
print "<html><head><title>Little funny fortunes</title></head>"
print "<body>"
print "<form>"




if os.environ.has_key("QUERY_STRING"):
	st = os.environ["QUERY_STRING"].split("m=")
	if len(st)==1:
		print '<p>Suchwort:<br><input name="m" type="text" size="30" maxlength="30">'
		print '<input type="submit" value=" Absenden "></p>'
	if len(st)==2:
		print '<p>Suchwort:<br><input name="m" type="text" size="30" maxlength="30" value = ',st[1],'>'
		print '<input type="submit" value=" Absenden "></p>'
		for e in bla:	
			if st[1] in e:
				c.append(e)
		if len(c)>0:
			print c[random.randint(0,len(c)-1)]
		else:
		        print 'No fortune found with "',st[1],'"'
	else:
		print bla[random.randint(0,len(bla)-1)]

print "</form>"
print "</body>"
print "</html>"
